package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.Member;
import com.sk.bilibili.dto.CoinInfo;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import com.sk.bilibili.utils.WarpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import com.sk.bilibili.bean.Coin;
import com.sk.bilibili.mapper.CoinMapper;

/**
 * @author 邵康
 * @date 2021/11/25 21:06
 */
@Service
public class CoinService extends ServiceImpl<CoinMapper, Coin> {

    @Autowired
    private MemberService memberService;
    @Autowired
    private WarpUtils warpUtils;
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(Coin coin) {
        updateById(coin);
        return R.success();
    }

    public R<IPage<Coin>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page, size), null));
    }

    public R<Void> add(Coin coin) {
        int memberId = BSessionUtils.getMemberId();
        if (hasCoin(memberId,coin.getType(),coin.getTargetId())) return R.error("不能重复投币");
        Member member = memberService.getById(memberId);
        if (member.getCoinNum() < coin.getNum()) return R.error("硬币数不足");
        coin.setMemberId(memberId);
        save(coin);
        eventPublisher.publishEvent(new BiliBiliEvent<>(this,coin).putExtra("memberId",memberId));
        return R.success();
    }

    //  投币 有额外信息 必须立即写入
    public Boolean hasCoin(int memberId,Integer type ,Integer targetId) {
        QueryWrapper<Coin> queryWrapper = QueryWrapperUtils.eq("member_id",
                memberId, "target_id", targetId, "type", type);
        return count(queryWrapper) > 0;
    }

    public R<IPage<Coin>> getCoinVideo(CoinInfo coinInfo) {
        if(coinInfo.getMemberId()==null)coinInfo.setMemberId(BSessionUtils.getMemberId());
        QueryWrapper<Coin> queryWrapper = QueryWrapperUtils.eq("member_id", coinInfo.getMemberId());
        IPage<Coin> iPage = page(coinInfo.page(), queryWrapper);
        iPage.getRecords().forEach(coin ->
                coin.getExtra().addExtra(warpUtils.getTypeTarget(coin.getType(),coin.getTargetId())));
        return R.success(iPage);
    }

}
